<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form
                :inline="true"
                ref="listForm"
                :rules="listRules"
                :model="listForm">
                <el-form-item prop="name">
                    <el-input clearable placeholder="请输入名称" v-model="listForm.name" style="width: 150px;" @keyup.enter.native="handleSearch" />
                </el-form-item>
                <el-button v-waves type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleBatch">批量添加</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleCreate">添加网址</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleCreateCategory">添加分类</el-button>
            </el-form>
        </div>
        <el-table
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width:100%;">
            <el-table-column label="编号" prop="id" align="center" min-width="100px" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{ scope.row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="名称" prop="id" align="left" min-width="200px" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="分类" prop="type" align="left" min-width="100px" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{ scope.row.categoryName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="链接" min-width="200px" align="left" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <a :href="scope.row.link" target="_blank" style="color: blue;">{{scope.row.link}}</a>
                </template>
            </el-table-column>
            <el-table-column label="简介" min-width="300px" align="left" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span>{{scope.row.intro}}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100px" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" size="mini">{{ scope.row.status | statusFilter }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="left" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.status!=2" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listForm.page"
            :limit.sync="listForm.pageSize"
            @pagination="getList"/>
        <el-dialog
            title="批量添加"
            :visible.sync="dialogBatchVisible"
            center>
            <el-form
                ref="batchForm"
                :rules="batchRules"
                :model="batchForm"
                label-position="left"
                style="margin-left:30px;margin-right:30px;">
                <el-form-item prop="list">
                    <el-input clearable type="textarea" :autosize="{ minRows: 5, maxRows: 10}" v-model="batchForm.list" placeholder="请输入数据，网址格式：[{categoryId:..., categoryName:..., logo:...,name:...,type:...,link:...,desc:...}]，分类格式：[{parentId:..., name:..., sort:...}]" style="width:100%;"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="batchData(1)">添加网址</el-button>
                <el-button type="primary" @click="batchData(2)">添加网址分类</el-button>
                <el-button @click="dialogBatchVisible = false">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog
            title="添加分类"
            :visible.sync="dialogCategoryVisible"
            center>
            <el-form
                ref="categoryForm"
                :rules="categoryRules"
                :model="categoryForm"
                label-position="left"
                style="margin-left:30px;margin-right:30px;">
                <el-form-item prop="parentId">
                    <el-select clearable v-model="categoryForm.parentId" placeholder="请选择父级分类" style="width: 100%;">
                        <el-option v-for="item in categoryMap" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="name">
                    <el-input clearable v-model="categoryForm.name" placeholder="请输入分类名称" style="width:100%;"/>
                </el-form-item>
                <el-form-item prop="sort">
                    <el-input clearable v-model.number="categoryForm.sort" placeholder="请输入排序序号" style="width:100%;"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="createCategoryData">确定</el-button>
                <el-button @click="dialogCategoryVisible = false">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog
            :title="textMap[dialogStatus]"
            :visible.sync="dialogFormVisible"
            center>
            <el-form
                ref="postForm"
                :rules="rules"
                :model="postForm"
                label-position="left"
                style="margin-left:30px;margin-right:30px;">
                <el-form-item prop="categoryId">
                    <el-select clearable v-model="postForm.categoryId" placeholder="请选择分类" style="width: 100%;">
                        <el-option v-for="item in categoryMap" :key="item.value" :label="item.name" :value="item.value" :disabled="item.value == 1" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="name">
                    <el-input clearable v-model="postForm.name" placeholder="请输入名称" style="width:100%;"/>
                </el-form-item>
                <el-form-item prop="logo">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :headers="myHeaders"
                        :data="{type: 'navi'}"
                        list-type="picture-card"
                        :show-file-list="false"
                        :on-success="handleUploadSuccess"
                        :before-upload="handleBeforeUpload">
                        <img v-if="postForm.logo" v-lazy="postForm.logo" :key="postForm.logo" style="max-width:100%;max-height:100%;">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M。</div>
                    </el-upload>
                    <el-input clearable v-model="postForm.logo" placeholder="logo" style="width:100%;"/>
                </el-form-item>
                <el-form-item prop="link">
                    <el-input v-model="postForm.link" placeholder="请输入链接" style="width:100%;"/>
                </el-form-item>
                <el-form-item prop="intro">
                    <el-input clearable type="textarea" :autosize="{ minRows: 3, maxRows: 5}" v-model="postForm.intro" placeholder="请输入简介" style="width:100%;"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    upload
} from '@/api/base';
import {
    list,
    add,
    update,
    remove,
    addCategory,
    listCategory
} from '@/api/serve/navi';
import {
    API_SERVER
} from '@/utils/config';
import waves from '@/directive/waves';
import Pagination from '@/components/Pagination';
import 'viewerjs/dist/viewer.css'
import Viewer from 'v-viewer'
import Vue from 'vue'
Vue.use(Viewer)

const categoryMap = [
    {name: '一级分类', value: 1}
];

const listForm = {
    page: 1,
    pageSize: 10
};
const postForm = {};
const batchForm = {};
const categoryForm = {};

export default {
    name: 'navi',
    filters: {
        statusFilter(status) {
            const statusMap = {
                '1': '正常',
                '2': '已删除'
            }
            return statusMap[status]
        }
    },
    directives: { waves },
    components: { Pagination },
    data() {
        const linkValidator = (rule, value, callback) => {
            if (value && !/(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/.test(value)) {
                return callback(new Error('请输入正确的链接'));
            }
            return callback();
        };
        const isArray = (data)=>{
            return Object.prototype.toString.call(data) === '[object Array]';
        }
        return {
            list: [],
            listLoading: true,
            listForm: Object.assign({}, listForm),
            total: 0,
            listRules: {
                name: [{max: 200, message: '不能超过200个字符', trigger: 'blur'}],
                type: [{max: 200, message: '不能超过200个字符', trigger: 'change'}]
            },

            categoryMap: Object.assign({}, categoryMap),
            dialogCategoryVisible: false,
            categoryForm: Object.assign({}, categoryForm),
            categoryRules: {
                parentId: [{required: true, message: '必选', trigger: 'change'}],
                name: [{required: true, message: '必填', trigger: 'blur'},
                    {max: 200, message: '不能超过200个字符', trigger: 'blur'}],
                sort: [{required: true, message: '必填', trigger: 'blur'},
                    {type: 'number', message: '请输入数字', trigger: 'blur'}]
            },

            dialogBatchVisible: false,
            batchForm: Object.assign({}, batchForm),
            batchRules: {
                list: [{required: true, message: '必填', trigger: 'blur'}]
            },

            myHeaders: { 'erp-token': 'admin' },
            uploadUrl: API_SERVER + '/base/upload',

            postForm: Object.assign({}, postForm),
            rules: {
                categoryId: [{required: true, message: '必选', trigger: 'change'}],
                name: [{ required: true, message: '必填', trigger: 'blur' },
                    {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}],
                logo: [{required: true, message: '必填', trigger: 'blur'},
                    {validator: linkValidator, trigger: 'blur'}],
                link: [{ required: true, message: '必填', trigger: 'blur' },
                    {validator: linkValidator, trigger: 'blur'}],
                intro: [{min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}]
            },
            textMap: {
                update: '更新',
                create: '新增'
            },
            dialogStatus: '',
            dialogFormVisible: false
        }
    },
    created() {
        this.getList();
    },
    methods: {
        getList() {
            this.listLoading = true;
            list(this.listForm).then(res => {
                this.list = res.data.list;
                this.total = res.data.total;
                this.listLoading = false;
            }).catch(err => {
                throw new Error('错误：' + err);
                this.listLoading = false;
            })
        },
        handleSearch() {
            this.listForm.page = 1
            this.getList()
        },
        handleBatch() {
            this.dialogBatchVisible = true;
            this.batchForm = Object.assign({}, batchForm);
        },
        handleCreate() {
            this.dialogStatus = 'create';
            this.dialogFormVisible = true;
            this.postForm = Object.assign({}, postForm);
            this.getCategory();
            this.$nextTick(() => {
                this.$refs['postForm'].clearValidate();
            });
        },
        handleCreateCategory() {
            this.dialogCategoryVisible = true;
            this.categoryForm = Object.assign({}, categoryForm);
            this.getCategory();
            this.$nextTick(() => {
                this.$refs['categoryForm'].clearValidate();
            });
        },
        handleDelete(row) {
            this.$confirm('确定要删除吗?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                remove({
                    ids: [row.id]
                }).then(() => {
                    this.dialogFormVisible = false
                    this.$notify({
                        title: '成功',
                        message: '操作成功',
                        type: 'success',
                        duration: 5000
                    });
                    this.listForm.page = 1;
                    this.getList();
                });
            });
        },
        handleUpdate(row) {
            this.postForm = Object.assign({}, row);
            this.dialogStatus = 'update';
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs['postForm'].clearValidate();
            });
        },
        getCategory() {
            listCategory().then(res => {
                let list = [];
                for (let item of res.data) {
                    list.push({
                        name: item.name,
                        value: item.id
                    });
                }
                this.categoryMap = categoryMap.concat(list);
            });
        },
        createCategoryData() {
            this.$refs['categoryForm'].validate((valid) => {
                if (valid) {
                    addCategory([this.categoryForm]).then(() => {
                        this.dialogCategoryVisible = false
                        this.$notify({
                            title: '成功',
                            message: '操作成功',
                            type: 'success',
                            duration: 5000
                        });
                    });
                }
            })
        },
        createData() {
            this.$refs['postForm'].validate((valid) => {
                if (valid) {
                    add([this.postForm]).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '操作成功',
                            type: 'success',
                            duration: 5000
                        });
                        this.listForm.page = 1;
                        this.getList();
                    })
                }
            })
        },
        batchData(data) {
            this.$refs['batchForm'].validate((valid) => {
                if (valid) {
                    try {
                        let list = JSON.parse(this.batchForm.list);
                        if (data == 1) {
                            add(list).then(() => {
                                this.$notify({
                                    title: '成功',
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 5000
                                });
                                this.listForm.page = 1;
                                this.getList();
                            })
                        } else if (data == 2) {
                            addCategory(list).then(() => {
                                this.$notify({
                                    title: '成功',
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 5000
                                });
                            });
                        }
                    } catch(err) {
                        this.$notify({
                            title: '失败',
                            message: '解析失败：' + err,
                            type: 'error',
                            duration: 5000
                        });
                    }
                }
            })
        },
        updateData() {
            this.$refs['postForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.postForm)
                    update(tempData).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '操作成功',
                            type: 'success',
                            duration: 5000
                        })
                        this.getList();
                    })
                }
            })
        },
        handleBeforeUpload(file) {
            const isImg = file.type.indexOf('image/') === 0
            const isLt5M = file.size / 1024 / 1024 < 5
            if (!isImg) {
                this.$message.error('只能上传图片!')
            }
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!')
            }
            return isImg && isLt5M;
        },
        handleUploadSuccess(res, file) {
            this.$message.success('Logo上传成功!')
            this.$set(this.postForm, 'logo', res.data.url);
        },
    }
}

</script>

<style lang="scss" scoped>
</style>
